<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { CustomDialogInstance } from '@/types'
import type { ApplicationModel } from '@/types/modules/application-models'

import { saveOrUpdateApplicationModel } from '@/api/modules/applicationModel'

defineProps<{
  modalTitle: string
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()
const dialogRef = ref<CustomDialogInstance>()
const formRef = ref<FormInstance>()

const info = defineModel<ApplicationModel>({
  required: true,
})
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '请输入模型名称',
    },
    {
      min: 2,
      max: 10,
      message: '长度在 2 到 10 个字符',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入模型编码',
    },
    {
      min: 2,
      max: 10,
      message: '长度在 2 到 10 个字符',
    },
    { validator: validateCode },
  ],
}

function validateCode(
  _rule: any,
  value: any,
  callback: any,
) {
  if (/\W+/.test(value)) {
    callback(new Error('编码只可包含数字、字母或下划线'))
  }
  else {
    callback()
  }
}

async function clickSave(done: () => void) {
  const isValid = await formRef.value
    ?.validate()
    .catch(() => {
      done()
    })
  if (isValid) {
    try {
      const { id, name, code } = unref(info)
      await saveOrUpdateApplicationModel({
        id: id === 0 ? undefined : id,
        name,
        code: code!,
      })
      done()
      close()
      ElMessage.success('保存成功')
      emits('save-success')
    }
    catch (e) {
      done()
    }
  }
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({ open, close })
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="600px"
    need-saving
    @confirm="clickSave"
  >
    <ElForm
      ref="formRef"
      :model="info"
      :rules="rules"
      label-position="top"
    >
      <ElFormItem label="模型名称" prop="name">
        <ElInput
          v-model.trim="info.name"
          :maxlength="10"
          :minlength="2"
          placeholder="请输入模型名称，字数不超过10个"
        />
      </ElFormItem>
      <ElFormItem label="模型编码" prop="code">
        <ElInput
          v-model.trim="info.code"
          :maxlength="10"
          :minlength="2"
          placeholder="请输入模型编码，可包含数字、字母或下划线，且长度不超过10"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
